<?php
// 线路控制器
class Controller_WWW_Track extends Controller_WWW_Template
{
    public function __construct ($req, $res)
    {
        $this->template = "smarty:www/track";
        parent::__construct($req, $res);
    }

    public function action_index($page = 1){
        $page     = max(1, $page);
        //$limit    = 3;
        //$offset   = $limit * ($page - 1);
        $track_limit = 5;
        $act_limit = 3;
        $track_offset= $track_limit * ($page-1);
        $act_offset= $act_limit * ($page-1);

        $activity = new App_Activity();
        list($activity_count,$list) = $activity->search(NULL,$act_offset,$act_limit);
        if(!empty($list) && count($list) < $act_limit){
             $new_act_offset=$act_offset-$act_limit+count($list);
             if($new_act_offset<0){
             $activity_count=null;$list=null;
             }else{
               list($activity_count,$list) = $activity->search(NULL,$new_act_offset,$act_limit);
             }
        }
        if(empty($list)){
             $activity_count=null;$list=null;
        }

        $track = new App_Track();
        list($counts,$tracks) = $track->search(NULL,$track_offset,$track_limit);
       // var_dump($tracks);exit();
        $this->template->set('tracks',$tracks);
        $this->template->set('activity_count',$activity_count);
        $this->template->set('counts',$counts);
        $this->template->set('activity',$list);
        $this->template->set('var_i',0);

        $countrys=App_Config::optionsCountryList();
        $citys=App_Config::optionsCityList();
        foreach($countrys as &$cou){
        	$cou=array("val"=>$cou,"selected"=>1);
        }
        foreach($citys as &$cit){
        	$cit=array("val"=>$cit,"selected"=>1);
        }
        $this->template->set('countrys',$countrys);
        $this->template->set('scitys',$citys);

        $pagination = $this->pagination($counts,$track_limit, $page_type = 'route', $page_key = 'param1', $views = 'www/page/new');
        $this->template->set('pagination', $pagination);
        $this->template->set('step','track');
    }

    public function action_search ($page = 1)
    {
        $query = $this->request->query();
        $scity = Arr::get($query,'city');
        $start = Arr::get($query,'start');
        $end = Arr::get($query,'end');
        $TouristCounts = Arr::get($query,'number');
        $fabu = Arr::get($query,'fabu');
        $age = Arr::get($query,'age');
        $gender = Arr::get($query,'gender');
        $identity = Arr::get($query,'identity');
        $language = Arr::get($query,'language');
        $chuxing = Arr::get($query,'chuxing');
        $people_num = Arr::get($query,'people_num');
        $price = Arr::get($query,'price');
        $orders = Arr::get($query,'orders');
        $score = Arr::get($query,'score');
        $scountry = Arr::get($query,'country');

        $page     = max(1, $page);
        //$limit    = 3;
        //$offset   = $limit * ($page - 1);
        $track_limit=5;
        $act_limit=3;
        $track_offset=$track_limit * ($page - 1);
        $act_offset=$act_limit * ($page - 1);

        $activity = new App_Activity();


        list($counts,$tracks) = App_Track_Search::getTrack($scity,$start,$end,$TouristCounts,$fabu,
            $age,$gender,$identity,$language,$people_num,$chuxing,$price,$orders,$score,$track_limit,$track_offset
        );

        if($counts){
            list($activity_count,$list) = $activity->search(NULL,$act_offset,$act_limit);
       //     if(empty($list) ||count($list) < $act_limit){
       //         list($activity_count,$list) = $activity->search(NULL,0,$act_limit);      
            if(!empty($list) && count($list) < $act_limit){
                  $new_act_offset=$act_offset-$act_limit+count($list);
                  if($new_act_offset<0){
                     $activity_count=null;$list=null;
                  }else{
                     list($activity_count,$list) = $activity->search(NULL,$new_act_offset,$act_limit);
                  }
            }
            if(empty($list)){
             $activity_count=null;$list=null;
            }
         
            $this->template->set('activity_count',$activity_count);
            $this->template->set('activity',$list);
        }

        $tracks = App_Track_Search::getRebuildData($tracks);
//        var_dump($tracks);
        $pagination = $this->pagination($counts, $track_limit, $page_type = 'route', $page_key = 'param1', $views = 'www/page/new');
        $this->template->set('pagination', $pagination);

        $this->template->set('tracks',$tracks);

        $this->template->set('counts',$counts);

        $this->template->set('var_i',0);

        $countrys=App_Config::optionsCountryList();
        if($scountry==-1){
        	$citys=App_Config::optionsCityList();
        }else{
        	$citys=App_Config::optionsCityListByCountry($scountry);
        }
        foreach($countrys as &$cou){
        	if($cou==$scountry)
        	{$cou=array("val"=>$cou,"selected"=>2);}
        	else{$cou=array("val"=>$cou,"selected"=>1);}
        }
        foreach($citys as &$cit){
        	if($cit==$scity)
        	{$cit=array("val"=>$cit,"selected"=>2);}
        	else{$cit=array("val"=>$cit,"selected"=>1);}
        }
        $this->template->set('countrys',$countrys);
        $this->template->set('scitys',$citys);

        $this->template->set('fabu',$fabu);
        $this->template->set('age',$age);
        $this->template->set('gender',$gender);
        $this->template->set('identity',$identity);
        $this->template->set('language',$language);
        $this->template->set('chuxing',$chuxing);
        //$this->template->set('scity',$city);
        $this->template->set('start',$start);
        $this->template->set('end',$end);
        $this->template->set('number',$TouristCounts);
        $this->template->set('price',$price);
        $this->template->set('orders',$orders);
        $this->template->set('score',$score);
        $this->template->set('people_num',$people_num);
        //$this->template->set('country',$country);
        $this->template->set('step','track');
        $this->template->set_filename('smarty:www/track_search');
    }

    // 线路详情
    public function action_detail ($trackId)
    {
        $track  = new App_Track($trackId);
        $detail = $track->detail();

        $tongji=array();
        if(!empty($detail['priceTotal'])){
        $tongji['food']=round($detail['priceFood']/$detail['priceTotal']*100);
        $tongji['traffic']=round($detail['priceTraffic']/$detail['priceTotal']*100);
        $tongji['ticket']=round($detail['priceTicket']/$detail['priceTotal']*100);
        $tongji['other']=round($detail['priceOther']/$detail['priceTotal']*100);
        $tongji['service']=round($detail['priceService']/$detail['priceTotal']*100);
        }else{
        $tongji['food']=0;
        $tongji['traffic']=0;
        $tongji['ticket']=0;
        $tongji['other']=0;
        $tongji['service']=0;
        }
        $this->template->set('tongji', $tongji);

        $comments = Comments::getActivityOrTrackComments($trackId,'track',5,0);
        foreach($comments as &$v){
            $v['tourist_pic'] = explode(';',$v['tourist_pic']);
        }
        $this->template->set("comments",$comments);
        $this->template->set_filename('smarty:www/track/track_detail');
        $this->template->set('track', $detail);
        $this->template->set('step','track');
        $this->template->set('counts', count($comments));

        // 导游空闲时间
        $this->template->set('guiderFreeDays', $track->getCurrentGuiderFreeDays());

        // 最大接待数量
        $maxPersons = Arr::get($detail, 'serviceMaxPersons', 0);
        $n = 1;
        $persons    = array();
        while ($n <= $maxPersons && $n <= 15)
        {
            $persons[] = $n;
            $n+= 1;
        }
        $this->template->set('personList', $persons);
    }

    //获取更多评论
    public function action_get_more($page = 2){
        $query = $this->request->query();
        $trackId = Arr::get($query,'id');
        $page   = max($page, 1);
        $limit  = 5;
        $offset = ($page - 1) * $limit;
        $comments = Comments::getActivityOrTrackComments($trackId,"track",$limit,$offset);
        $this->template->set_filename('smarty:www/activity/item');
        $this->template->set('comments',$comments);
        $rs = $this->template->render();

        echo $rs;
        exit;
    }

    // 线路详情页之行程单详情
    public function action_detail_days ($trackId)
    {
        $track  = new App_Track($trackId);
        $detail = $track->detail();
        $days   = $track->days();

        $address = array();
        foreach($days as $day){
            $address['day'.$day['dayNo']][] = array(
                'id'=>$day['id'],
                'address'=>$day['address'],
                'lat'=>$day['lat'],
                'lng'=>$day['lng'],
            );
        }

        $this->template->set('address', json_encode($address));
        $dates  = array();
        foreach ($days as $day)
        {
            $dayNo = Arr::get($day, 'dayNo');
            if (! isset($dates[$dayNo]))
                $dates[$dayNo] = "第{$dayNo}天";
        }
        $dates[999] = "旅行结束";
        
        foreach($days as &$val){
          $data=explode(':',$val['timeStart']);
          $val['timeStart']=$data[0].":".$data[1];
          $data=explode(':',$val['timeStop']);
          $val['timeStop']=$data[0].":".$data[1];
          }
        unset($val);
      
        $this->template->set_filename('smarty:www/track/track_detail_days');
        $this->template->set('track', $detail);
        $this->template->set('days', $days);
        $this->template->set('dates', $dates);
        $this->template->set('day_num', 1);
        $this->template->set('step','track');
    }

    // 创建
    public function action_create ()
    {
        $this->request->redirect('/track/create_basic');
    }

    // 删除
    public function action_remove ($trackId)
    {
        $track = new App_Track($trackId);
        $detail = $track->detail();
        $uid    = Arr::get($detail, 'uid');
        if ($uid > 0 && $uid == $this->_uid)
        {
            $track->remove();
        }

        $referrer = $this->request->referrer();
        $this->request->redirect($referrer);
    }

    public function action_create_basic ($trackId = NULL)
    {
        $post = $this->_post;
        if (empty($post))
        {
            $cityList=App_City::getCityListCn();
            $this->template->set('cityList',$cityList);
            $this->template->set_filename('smarty:www/track/create');

            if ($trackId > 0)
            {
                $track = new App_Track($trackId);
                $track_data=$track->detail();
                $this->template->set('track', $track_data);
            }
        }
        else
        {
            $uid    = $this->_uid;
            $srv70s = (int) Arr::get($post, 'support70s', 0);
            $srv80s = (int) Arr::get($post, 'support80s', 0);
            $srv90s = (int) Arr::get($post, 'support90s', 0);
            $srv00s = (int) Arr::get($post, 'support00s', 0);

            $sptCar = (int) Arr::get($post, 'trafficSupportCar', 0);
            $sptBus = (int) Arr::get($post, 'trafficSupportBus', 0);

            $srvMin = (int) Arr::get($post, 'serviceMinPersons', 0);
            $srvMax = (int) Arr::get($post, 'serviceMaxPersons', 0);
    
            $city   = trim(Arr::get($post, 'city'));
            $cityId   = (int)Arr::get($post, 'cityId');
            $country= trim(Arr::get($post, 'country'));
            $days   = trim(Arr::get($post, 'days'));

            $build  = new App_Track_Build;
            if ($trackId > 0)
            {
                $build->updateBasic($trackId, $uid, $country, $city,$cityId, $sptCar, $sptBus, $srv70s, $srv80s, $srv90s, $srv00s, $srvMin, $srvMax, $days);
                $tid = $trackId;
            }
            else
            {
                $tid    = $build->createByBasic($uid, $country, $city,$cityId, $sptCar, $sptBus, $srv70s, $srv80s, $srv90s, $srv00s, $srvMin, $srvMax, $days);
            }

            if ($tid > 0)
                $this->request->redirect('/track/create_days/'.$tid);
            else
                $this->request->redirect('/track/create_basic');
        }
    }

    public function action_create_days($trackId)
    {
        $post = $this->_post;
        if (empty($post))
        {
            $track = new App_Track($trackId);
            $track_data=$track->detail();
            $this->template->set('track', $track_data);

            $daysList = $track->scenicListByDay();
            $this->template->set('daysList', $daysList);

            $scenic = new ScenicSpot;
            $scenicList = $scenic->validListByTrack($trackId, $this->_uid, $track_data['cityId']);
           
            $this->template->set('scenicList', $scenicList);

            $this->template->set('trackid',$track_data['id']); 
            $this->template->set('step', 'days');
            $this->template->set_filename('smarty:www/track/create');
        }
        else
        {
            $name    = trim(Arr::get($post, 'name'));
            $summary = trim(Arr::get($post, 'summary'));
            //web图片
            list($thumbUrl, $thumbPos)   = Media::save_upload_file('thumb', Kohana::config('env.image.track_thumb'));
            list($bannerUrl, $bannerPos) = Media::save_upload_file('bannerUrl', Kohana::config('env.image.track_banner'));
//             //app图片
//             $bannerAppUrl='';
//             if(!empty($bannerUrl)){
//             	$url = DOCROOT.'/'.$bannerUrl;
//             	$image = Image::factory($url);
            	
//             	$items = explode('.', $url);
//             	$suffix = $items[count($items) - 1];
//             	$suffix = strtolower($suffix);
            	
//             	$file_name = md5(time().$url).".".$suffix;
//             	$file_url = DOCROOT.'/upload/app/'.$file_name;
//             	$file_pos= '/upload/app/'.$file_name;
            	
//             	$config = Kohana::config('env.image.track_app_banner');
//             	$is_save=file_put_contents($file_url,$image->resize($config['width'], $config['height'], $config['master'])->render());
//             	if($is_save){
//             		$bannerAppUrl=$file_pos;
//             	}
//             }            
            // 景点
            $scenics = array();
            foreach ($post as $key => $val)
            {
                if (preg_match('/^scenic_(\d+)_(\d+)$/', $key, $m))
                {
                    $scenicId = (int) $m[1];
                    $dayNo    = (int) $m[2];
                    $arrVal   = @json_decode($val, TRUE);
                    $scenics[] = array(
                        'scenicId' => $scenicId,
                        'dayNo'    => $dayNo,
                        'startTime'=> Arr::get($arrVal, 'startTime'),
                        'stopTime' => Arr::get($arrVal, 'stopTime'),
                        'desc'     => Arr::get($arrVal, 'desc'),
                    );
                }
            }

            $build   = new App_Track_Build;
            if ($build->updateDays($trackId, $name, $summary, $thumbUrl, $bannerUrl, $scenics))
            {
                $this->request->redirect('/track/create_times/'.$trackId);
            }
            else
            {
                $this->request->redirect('/track/create_days/'.$trackId);
            }
        }
    }

    public function action_create_price ($trackId)
    {
        $post = $this->_post;
        if (empty($post))
        {
            $track = new App_Track($trackId);
            $this->template->set('track', $track->detail());
            $this->template->set('daysService', $track->getDaysService());
            $this->template->set('step', 'price');
            $this->template->set_filename('smarty:www/track/create');
        }
        else
        {
            $uid    = $this->_uid;

            $priceService = (int) (Arr::get($post, 'priceService'));

            $priceTicket  = (int) (Arr::get($post, 'priceTicket'));
            $descTicket   = trim(Arr::get($post, 'descTicket'));

            $priceFood    = (int) (Arr::get($post, 'priceFood'));
            $descFood     = trim(Arr::get($post, 'descFood'));

            $priceTraffic = (int) (Arr::get($post, 'priceTraffic'));
            $descTraffic  = trim(Arr::get($post, 'descTraffic'));

            $priceOther   = (int) (Arr::get($post, 'priceOther'));
            $descOther    = trim(Arr::get($post, 'descOther'));

            $build  = new App_Track_Build;
            if ($build->updatePrice($trackId, $priceTraffic, $priceTicket, $priceFood, $priceService, $priceOther,
                        $descFood, $descTraffic, $descTicket, $descOther))
            {
                $this->request->redirect('/track/create_bank/'.$trackId);
            }
            else
            {
                $this->request->redirect('/track/create_price/'.$trackId);
            }
        }
 
    }

    public function action_create_times ($trackId)
    {
        $post = $this->_post;
        if (empty($post))
        {
            $this->template->set('step', 'times');
            $this->template->set_filename('smarty:www/track/create');

            $track = new App_Track($trackId);
            $this->template->set('track', $track->detail());
        }
        else
        {
            $startDay = trim(Arr::get($post, 'startDay'));
            $stopDay  = trim(Arr::get($post, 'stopDay'));
            $freeDays = trim(Arr::get($post, 'freeTimeDays'));

            $build  = new App_Track_Build;
            if ($build->updateTimes($trackId, $startDay, $stopDay, $freeDays))
            {
                $this->request->redirect('/track/create_price/'.$trackId);
            }
            else
            {
                $this->request->redirect('/track/create_times/'.$trackId);
            }
        }
 
    }

    public function action_create_bank ($trackId)
    {
        $post = $this->_post;
        if (empty($post))
        {
            $bank = new UserExt_BanK($this->_uid);
            $blist=$bank->getBankList();
            $track = new App_Track($trackId);
            $tdetail=$track->detail();
            $accountdf=array();
            $bchoosen=array();
            if(!empty($tdetail['accountUserName'])){
               $bchoosen['accountUserName']=$tdetail['accountUserName'];
               $bchoosen['accountType']=$tdetail['accountType'];
               $bchoosen['accountName']=$tdetail['accountName'];
               foreach($blist as &$val)
               {
            	    if($val['accountUserName']==$tdetail['accountUserName'])
            	    {$val=array();}
               }
               unset($val);
            }else{
            	foreach($blist as &$val)
            	{
            		if($val['isDefault'])
            		{$accountdf=$val;$val=array();}
            	}
               unset($val);
            }
            $this->template->set('bankList', $blist);
            $this->template->set('accountdf', $accountdf);
            $this->template->set('bankchoosen', $bchoosen);
            $this->template->set('step', 'bank');
            $this->template->set('track', $tdetail);
            $this->template->set_filename('smarty:www/track/create');

        }
        else
        {
            $accountType     = trim(Arr::get($post, 'accountType'));
            $accountName     = trim(Arr::get($post, 'accountName'));
            $accountUserName = trim(Arr::get($post, 'accountUserName'));

            $build  = new App_Track_Build;
            if ($build->updateBank($trackId, $accountType, $accountName, $accountUserName))
            {
                $this->request->redirect('/track/create_succ/'.$trackId);
            }
            else
            {
                $this->request->redirect('/track/create_bank/'.$trackId);
            }
        }
    }

    // 发布路线成功
    public function action_create_succ ($trackId)
    {
        $post = $this->_post;
        if (empty($post))
        {
            $track = new App_Track($trackId);
            $popularize = new Popularize;

            $this->template->set('step', 'succ');
            $this->template->set('track', $track->detail());
            $this->template->set('canRequestSubmittedPrize', $track->canRequestSubmittedPrize($this->_uid));
            $this->template->set('inviteCode', $popularize->getInviteCode($this->_uid));
            $this->template->set_filename('smarty:www/track/create');
        }
    }

    public function action_ajax_scenic_add ()
    {
        $row = array(
            'name'    => Arr::get($this->_post, 'name'),
            'address' => Arr::get($this->_post, 'address'),
            'subTitle'=> Arr::get($this->_post, 'subTitle'),
            'summary' => Arr::get($this->_post, 'summary'),
            'images'  => NULL,
        );

        $scenic = new ScenicSpot;
        $id     = $scenic->addByGuider($this->_uid, $row);

        Kohana::$log->add(Log::DEBUG, print_r($row, TRUE));
        echo json_encode(array( 'status' => 0,
            'name'    => $row['name'],
            'iconUrl' => '/resource/www/imgs/icon/10.png',
            'id'      => $id,
            ));exit;
    }
    
   // public function action_ajax_getCitysByCountry ()
   // {   $post = $this->request->post();
   //     $country=Arr::get($post, 'country');
   // 	$citys=App_Config::optionsCityListByCountry($country);
   // 	echo json_encode($citys);
   //     //return;
   // }
}
